<?php


namespace app\api\middleware;


use alipay\Auth;
use app\admin\model\UserBase;
use app\common\traits\JumpTrait;
use EasyWeChat\Factory as WechatFactory;
use think\facade\Session;
use think\Model;
use think\Request;

/**
 * 登录验证
 * Class TokenCheck
 * @package app\wechat\middleware
 */
class TokenCheck
{
    use JumpTrait;
    
    public function handle(Request $request, \Closure $next)
    {
        $client_type = session('client_type');
        if ($client_type == 'alipay') {//支付宝授权
//            session('alipay_user', null);
            if (empty(session('alipay_user'))) {//未登录状态
                $auth_code = input('auth_code');
                if (!$auth_code) {//没有授权码
                    $alipay_config = config('alipay');
                    $auth_url = sprintf($alipay_config['auth_url'], config('alipay.app_id'), 'auth_base', $request->url(true));
                    $this->redirect($auth_url);
                }
//                dd($auth_code);
                $auth_server = new Auth();
                $user = $auth_server->getuserid($auth_code);
                if (isset($user->user_id)) {//获取支付宝user_id
                    session('alipay_user', ['openid' => $user->user_id]);
                    Session::save();
                    $this->redirect($request->url(true));
                } else {
                    $this->error('用户授权失败');
                }
            } else {//已登录，自动注册或获取会员信息
                $user = session('alipay_user');
                $user_info = UserBase::init()->where('openid', $user['openid'])->find();
//                $user['area'] = ($user['raw']['country'] . $user['raw']['province'] . $user['raw']['city']) ?? '';
                if (!$user_info) {//系统中第一次出现，注册
                    $user['user_id'] = UserBase::init()->addUserByOpenId($user['openid'], ['client_type' => 2]);
                    $this->redirect($request->url(true));
                    $request->user = $user;
                } else {//更新信息
                    $request->user = $this->update_user_session($user_info, $user, 'alipay');
                }
            }
        } elseif ($client_type == 'wechat') {//微信授权
            $wechat_config = [
                'app_id' => env('WECHAT.APP_ID'),
                'secret' => env('WECHAT.SECRET'),
            ];
            $wechat = WechatFactory::officialAccount($wechat_config);
            if (empty(session('wechat_user'))) {//未登录
                session('target_url', $request->url(true));
                Session::save();
                //未登录状态重定向到授权页面
                $login_url = $wechat->oauth->scopes(['snsapi_userinfo'])
                    ->redirect(get_api_url('wechat_login', 'api'));
//                dd(session('wechat_user'), urldecode($login_url));
                $this->redirect(urldecode($login_url));
            } else {//已登录，自动注册或获取会员信息
                $user = session('wechat_user');
                $user_info = UserBase::init()->where('openid', $user['id'])->find();
                $user['area'] = ($user['raw']['country'] . $user['raw']['province'] . $user['raw']['city']) ?? '';
                if (!$user_info) {//系统中第一次出现，注册
                    $ex_data = [
                        'nickname' => $user['nickname'],
                        'avatar_img' => $user['avatar'],
                        'area' => $user['area'],
                    ];
                    $user['user_id'] = UserBase::init()->addUserByOpenId($user['id'], $ex_data);
                    $request->user = $user;
                } else {//更新信息
                    $request->user = $this->update_user_session($user_info, $user, 'wechat');
                }
            }
        }

        return $next($request);
    }

    /**
     * @title 更新session和数据库中的用户信息
     * @param Model $old
     * @param $new
     * @param string $type
     * @author FashionJune
     */
    protected function update_user_session(Model $old, $new, $type = 'wechat')
    {
        $update_data = [];
        (($new['nickname'] ?? '') != $old['nickname']) && ($update_data['nickname'] = $new['nickname']);
        (($new['avatar'] ?? '') != $old['avatar_img']) && ($update_data['avatar_img'] = $new['avatar']);
        (($new['area'] ?? '') != $old['area']) && ($update_data['area'] = $new['area']);
        $update_data && ($old->save($update_data));
        //更新session
        $new['user_id'] = $old['id'];
        $author_list = str2arr($old['user_author']);
        $new['author_list'] = $old['user_author'];
        $new['is_merchant'] = in_array('2', $author_list);
        $new['is_admin'] = in_array('3', $author_list);
        session($type . '_user', $new);
        Session::save();
        return $new;
    }

}